package com.mediacloud.app.newsmodule.fragment.simulcast

import android.annotation.SuppressLint
import android.view.View
import com.haibin.calendarview.BaseMonthView
import com.haibin.calendarview.CalendarView
import com.mediacloud.app.assembly.util.Utility
import com.mediacloud.app.model.fragment.LBottomSheetFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi
import com.mediacloud.app.quanzi.model.BaseDataBean
import com.mediacloud.app.quanzi.model.BaseDataListBean
import com.mediacloud.app.reslib.enums.XKey
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.tencent.mmkv.MMKV
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.simulcast_caleandar_sheet.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.text.DecimalFormat
import java.util.*

class SimulcastCalendarSheet : LBottomSheetFragment() {
    val decimalFormat = DecimalFormat("00")
    var call: SelectedCall? = null
    var nid: String? = null
    val schemes: MutableMap<String, MutableMap<String, com.haibin.calendarview.Calendar>?> = HashMap()
    var year = 0
    var month = 0
    var day = 0

    var currentYear = 0
    var currentMonth = 0
    var currentDay = 0
    var targetDate: String? = null
    private var mCurrentShowYear:Int=0

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(mRootView: View) {

        nid = requireArguments().getString("NID")
        year = requireArguments().getInt("year", 0)
        mCurrentShowYear=year
        month = requireArguments().getInt("month", 0)
        day = requireArguments().getInt("day", 0)

        val calendar = Calendar.getInstance()
        calendar.time = Date()
        currentYear = calendar.get(Calendar.YEAR)
        currentMonth = calendar.get(Calendar.MONTH) + 1
        currentDay = calendar.get(Calendar.DAY_OF_MONTH)

        calendarView?.setRange(currentYear - 10, 1, 1, currentYear, currentMonth, calendar.getActualMaximum(Calendar.DAY_OF_MONTH))

        calendarView?.scrollToCalendar(year, month, day)

        calendarTitleTv?.text = "$year.${decimalFormat.format(month)}"
        calendarView?.setOnMonthChangeListener { year, month ->
            calendarTitleTv?.text = "$year.${decimalFormat.format(month)}"
            getDate("$year-${decimalFormat.format(month)}")
        }

        //   val selected = Calendar.getInstance();
        val end = Calendar.getInstance()

        end.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        calendarView?.setOnCalendarInterceptListener(object : CalendarView.OnCalendarInterceptListener {
            override fun onCalendarIntercept(calendar: com.haibin.calendarview.Calendar): Boolean {

                if (calendar.year == year && calendar.month == month && calendar.day == day) {
                    return false
                }

                if (targetDate != null) {
                    if ("${calendar.year}${calendar.month}${calendar.day}" == targetDate) {
                        return false
                    }
                }
                return !calendar.hasScheme()
            }


            override fun onCalendarInterceptClick(calendar: com.haibin.calendarview.Calendar?, isClick: Boolean) {

            }
        })
        calendarView?.setOnCalendarSelectListener(object : CalendarView.OnCalendarSelectListener {
            override fun onCalendarOutOfRange(calendar: com.haibin.calendarview.Calendar?) {

            }

            override fun onCalendarSelect(calendar: com.haibin.calendarview.Calendar, isClick: Boolean) {
                year = calendar.year
                mCurrentShowYear=year
                month = calendar.month
                day = calendar.year
                if (targetDate != null) {
                    targetDate = null
                    return
                }
                call?.onSelected(calendar)
                dismiss()
            }
        })
        lastYearTv?.setOnClickListener {
            //修复当前的月份滚动到上一年的时候有选中，错误的问题（实际未选中），如果更改颜色就没选中效果了 修复如下：
            calendarView?.minRangeCalendar?.let { minCalendar->
                if (minCalendar.year<mCurrentShowYear){
//                    mCurrentShowYear--
                    calendarView?.monthViewPager?.let {
                        val view: BaseMonthView = it.findViewWithTag(it.getCurrentItem())
                        if (view != null) {

                            var mItems: MutableList<com.haibin.calendarview.Calendar>? =
                                Utility.invokeFiled<MutableList<com.haibin.calendarview.Calendar>>(
                                    view,
                                    "mItems"
                                )
                            if (mItems!=null&&mItems.size>0){
                                val diffMonth=getMonthDiff(mItems[0],minCalendar)
                                if (diffMonth >= 12) {
                                    //相差月份大于、等于12的时候才切换  然后通过月份切换
                                    it.setCurrentItem(it.getCurrentItem() - 12, false)
                                    mCurrentShowYear--
                                }

                            }

                        }
                    }
                }
            }

        }

        nextYearTv?.setOnClickListener {
            //修复当前的月份滚动到下一年的时候有选中，错误的问题（实际未选中），如果更改颜色就没选中效果了 修复如下：
            calendarView?.maxRangeCalendar?.let { maxCalendar->
                if (maxCalendar.year>mCurrentShowYear){
//                    mCurrentShowYear++
                    calendarView?.monthViewPager?.let {
                        val view: BaseMonthView = it.findViewWithTag(it.getCurrentItem())
                        if (view != null) {

                            var mItems: MutableList<com.haibin.calendarview.Calendar>? =
                                Utility.invokeFiled<MutableList<com.haibin.calendarview.Calendar>>(
                                    view,
                                    "mItems"
                                )
                            if (mItems!=null&&mItems.size>0){
                                val diffMonth=getMonthDiff(maxCalendar,mItems[0])
                                if (diffMonth>=12){
                                    //相差月份大于、等于12的时候才切换  然后通过月份切换
                                    it.setCurrentItem(it.getCurrentItem() + 12, false)
                                    mCurrentShowYear++
                                }
                            }

                        }
                    }
                }
            }

        }
        lastMonthTv?.setOnClickListener {
            //修复当前的月份滚动到上月的时候有选中，错误的问题（实际未选中），如果更改颜色就没选中效果了 修复如下：
            calendarView?.scrollToPre()
            calendarView?.monthViewPager?.let {
                val view: BaseMonthView = it.findViewWithTag(it.getCurrentItem())
                if (view != null) {
                    var mItems: MutableList<com.haibin.calendarview.Calendar>? =
                        Utility.invokeFiled<MutableList<com.haibin.calendarview.Calendar>>(
                            view,
                            "mItems"
                        )
                    if (mItems!=null&&mItems.size>0){
                        if (mItems[0].year!=mCurrentShowYear) {
                            mCurrentShowYear = mItems[0].year
                        }
                    }
                }
            }


        }
        nextMonthTv?.setOnClickListener {
            //修复当前的月份滚动到下月的时候有选中，错误的问题（实际未选中），如果更改颜色就没选中效果了 修复如下：
            calendarView?.scrollToNext()
            calendarView?.monthViewPager?.let {
                val view: BaseMonthView = it.findViewWithTag(it.getCurrentItem())
                if (view != null) {
                    var mItems: MutableList<com.haibin.calendarview.Calendar>? =
                        Utility.invokeFiled<MutableList<com.haibin.calendarview.Calendar>>(
                            view,
                            "mItems"
                        )
                    if (mItems!=null&&mItems.size>0){
                        if (mItems[0].year!=mCurrentShowYear) {
                            mCurrentShowYear = mItems[0].year
                        }
                    }
                }
            }


        }

        if(MMKV.defaultMMKV().getBoolean(XKey.DARK_MODE,false)){
            dark_mask.visibility = View.VISIBLE
        }else{
            dark_mask.visibility = View.GONE
        }

        getDate("$year-${decimalFormat.format(month)}")
    }
    /**
     * 获取两个日期相差的月数
     */
    fun getMonthDiff(calendar1:com.haibin.calendarview.Calendar,  calendar2:com.haibin.calendarview.Calendar):Int {
        var c1 = Calendar.getInstance();
        var c2 = Calendar.getInstance();
        c1.timeInMillis=calendar1.timeInMillis
        c2.timeInMillis=calendar2.timeInMillis
        var year1 = c1.get(Calendar.YEAR)
        var year2 = c2.get(Calendar.YEAR)
        var month1 = c1.get(Calendar.MONTH)
        var month2 = c2.get(Calendar.MONTH)
        var day1 = c1.get(Calendar.DAY_OF_MONTH)
        var day2 = c2.get(Calendar.DAY_OF_MONTH)
        // 获取年的差值?
        var yearInterval = year1 - year2
        // 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数
        if (month1 < month2 || month1 == month2 && day1 < day2) {
            yearInterval--
        }
        // 获取月数差值
        var monthInterval = (month1 + 12) - month2
        if (day1 < day2) {
            monthInterval--
        }
        monthInterval %= 12
        var monthsDiff = Math.abs(yearInterval * 12 + monthInterval)
        return monthsDiff
    }

    override fun onLayoutRes(): Int {
        return R.layout.simulcast_caleandar_sheet
    }

    interface SelectedCall {
        fun onSelected(calendar: com.haibin.calendarview.Calendar?)
    }

    private fun getDate(date: String) {
        val scheme = schemes[date]
        scheme?.let {
            calendarView.setSchemeDate(it)
            return
        }

        SpiderCmsApi.getSpiderCmsApi(requireContext()).getCatalogDate(nid, "$date-01", "$date-31")
            .enqueue(object : Callback<BaseDataBean<List<DateBean>>> {
                override fun onResponse(
                    call: Call<BaseDataBean<List<DateBean>>>,
                    response: Response<BaseDataBean<List<DateBean>>>
                ) {
                    if (response.isSuccessful && response.body()?.isSuccess == true) {
                        response.body()?.data?.let{data->
                            val scheme: MutableMap<String, com.haibin.calendarview.Calendar> = HashMap()
                            val size = data.size
                            for (i in 0 until size) {
                                if (data[i].hasNews)
                                    scheme[data[i].dateTime.replace("-", "")] = com.haibin.calendarview.Calendar()
                            }
                            schemes[date] = scheme
                            calendarView?.setSchemeDate(scheme)
                        }


                    }
                }

                override fun onFailure(call: Call<BaseDataBean<List<DateBean>>>, t: Throwable) {

                }

            })
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}